/*
 * Auto Currency Converter
 * -------------------------------------------------------------------
 * Licensed under the GPLv3 license, see LICENSE in root for details.
 *
 * main.js
 *
 * Copyright (c) 2010 Thomas Klein
 */

var symbol = "";
var toeurorate;
var nativerate;

chrome.extension.onRequest.addListener(
	function(request, sender, sendResponse)
	{
		sendResponse({});
		if(request.site = "amazon")
		{
			symbol = request.currency;
			toeurorate = request.erate;
			nativerate = request.nrate;
			convertPriceAmazon();
		}
	}
);

function calculatePrice(actual)
{
	return (Math.round((parseFloat(actual)/parseFloat(toeurorate))*parseFloat(nativerate)*100)/100);
}

function convertPriceAmazon()
{
	console.log("Symbol "+symbol+" Eurorate "+toeurorate+" nativrate "+nativerate);
	//var i=0;
	var curprice="";
	//convert big price tag
	var html = document.getElementsByClassName("priceLarge");
	if(html.length != 0)
	{
		curprice = html[0].innerHTML;
		html[0].innerHTML = html[0].innerHTML+" ["+calculatePrice(curprice.substring(1))+" "+symbol+"]";
		console.log("priceLarge: "+calculatePrice(curprice.substring(1)));
	}

	//convert other price tags
	console.log("sfsf");
	var price_html = document.getElementsByClassName("price");
	console.log("price length: "+price_html.length);
	if(price_html.length != 0)
	{
		for(var i = 0; i< price_html.length; i++)
		{
			//console.log(i+" "+html[i].innerHTML);
			//some are enclosed in <b> tags
			if(price_html[i].firstChild == null)
			{
				curprice = price_html[i].innerHTML;
				//console.log("price: "+calculatePrice(curprice.substring(1)));
				hprice_tml[i].innerHTML = price_html[i].innerHTML+" ["+calculatePrice(curprice.substring(1))+" "+symbol+"]";
			}
			else
			{
				curprice = price_html[i].firstChild.innerHTML;
				//console.log("price: "+calculatePrice(curprice));
				price_html[i].firstChild.innerHTML = price_html[i].firstChild.innerHTML+" ["+calculatePrice(curprice.substring(1))+" "+symbol+"]";
			}
		}
	}

	html = document.getElementsByClassName("red t14");
	console.log("red t14: "+html.length);
	if(html.length != 0)
	{
		for(var i = 0; i< html.length; i++)
		{
			curprice = html[i].innerHTML;
			console.log("price: "+calculatePrice(curprice));
			html[i].innerHTML = html[i].innerHTML+" ["+calculatePrice(curprice.substring(1))+" "+symbol+"]";
		}
	}
}


